<template>
  <card one="个人中心" two="更换头像">
    <template #main>
      <div class="avatar-box">
        <img :src="userImg" alt="" />
      </div>
      <div class="btns">
        <!-- 文件选择框 -->
        <input
          type="file"
          accept="image/*"
          style="display: none"
          ref="fileRef"
          @change="chooseImg"
        />
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="$refs.fileRef.click()"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="isDisabled"
          @click="updataImg"
          >上传头像
        </el-button>
      </div>
    </template>
  </card>
</template>

<script>
import ImgDefault from '@/assets/images/bg1.jpeg'
import { mapState, mapActions } from 'vuex'
import { upAvator } from '@/api/user'
export default {
  name: '',
  data () {
    return {
      userImg: '',
      isDisabled: true
    }
  },
  created () {
    setTimeout(() => {
      this.userImg = this.userInfo.user_pic || ImgDefault
    }, 1000)
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    ...mapActions('user', ['getMsg']),
    chooseImg (e) {
      const file = e.target.files[0]
      if (!file) return this.$message.error('请选择头像')
      if (file / 1024 / 1024 > 2) return this.$message.error('头像过大')
      const fr = new FileReader()
      fr.readAsDataURL(file)
      fr.onload = () => {
        this.userImg = fr.result
        this.isDisabled = false
      }
    },
    async updataImg () {
      const { data } = await upAvator(this.userImg)
      if (data.code !== 0) return this.$message.error(data.message)
      this.$message.success(data.message)
      this.isDisabled = true
      this.getMsg()
    }
  }
}
</script>
<style lang='less'  scoped>
.avatar-box {
  img {
    width: 350px;
    height: 350px;
    object-fit: cover;
  }
}
</style>
